package com.version1_3_1.service.implement;

import com.google.gson.internal.LinkedTreeMap;
import com.util.format.MapToJson;
import com.version1_3.dao.ActivityDao;
import com.version1_3.dao.UserDao1_3;
import com.version1_3.service.ActivityService;
import com.version1_3_1.dao.ActivityDaoFixed;
import com.version1_3_1.service.ActivityServiceFixed;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Created by reeveslee on 16/4/20.
 */
@Service
public class ActivityServiceFixedImpl implements ActivityServiceFixed {
    private static final Logger LOGGER = Logger.getLogger(ActivityServiceFixedImpl.class);

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ActivityDao activityDao;

    @Autowired
    private ActivityDaoFixed activityDaoFixed;

    @Autowired
    private UserDao1_3 userDao13;


    /**
     * 打卡界面
     *
     * @param activityId
     * @param userId
     * @return
     */
    @Override
    public String activityPage(int activityId, int userId) {
        // 发送数据Map
        Map<String, Object> activityPageMap = new HashMap<>();

        Map launchPageInfoMap = activityDao.getUserLaunchPageInfo(userId, activityId);

        /**
         * 用户一周的打卡情况
         */
        List<Map<String, Object>> weekLaunchInfo = activityDao.getUserWeekLaunchInfo(userId, activityId);
        int[] weekLaunchTag = new int[7];
        activityService.freshWeekLaunchTag(weekLaunchTag, weekLaunchInfo);


        /**
         * 公共数据设置
         */
        activityPageMap.put("days", launchPageInfoMap.get("days")); // 活动坚持天数
        activityPageMap.put("coin", launchPageInfoMap.get("coin")); // 活动积分
        activityPageMap.put("moneyCount", new DecimalFormat("#.00").format(activityDao.getUserDonateMoneyCount(userId))); // 所有活动捐献金额累积
        activityPageMap.put("money", launchPageInfoMap.get("money")); // 活动捐献金额
        activityPageMap.put("todayCount", 0); // 今日累积数据


        java.util.Date date = (java.util.Date) launchPageInfoMap.get("date");
        long time = Calendar.getInstance().getTime().getTime() - date.getTime();


        /**
         * 其他数据设置
         */
        if (time >= 0 && time <= 86400000) {
            /**
             * 今天已打卡
             */
            if (activityId == 11) {
                // 公益跑

                Map<String, Object> userBodyInfoMap = userDao13.getUserBodyInfo(userId); // 获取身高体重信息,用来计算跑路里程和卡路里
                Map gongyipaoMapFixed = activityDaoFixed.getGongyipaoLaunchCardInfoFixed(userId);
                activityPageMap.put("mileCount", gongyipaoMapFixed.get("mileCount"));
                activityPageMap.put("calorie", ((BigDecimal) userBodyInfoMap.get("weight")).intValue() * ((BigDecimal) gongyipaoMapFixed.get("mileCount")).doubleValue());
                activityPageMap.put("timeCount", gongyipaoMapFixed.get("timeCount"));
            }

            if (activityId == 12) {
                // 骑行
                activityPageMap.put("currMileNumber", launchPageInfoMap.get("currData"));
                activityPageMap.put("mileCount", launchPageInfoMap.get("currDataCount"));
            }

            if (activityId == 13) {
                // 平板支撑
                activityPageMap.put("topRecord", (BigDecimal) launchPageInfoMap.get("maxCurrData")); // 发送时间为long类型的最高数据
                long data3 = (long) launchPageInfoMap.get("data3");
                activityPageMap.put("todayCount", data3 * 100); // 今日累积坚持秒数

                data3 = (data3 > 810) ? 810 : data3; // 每日捐献金额有限制
                activityPageMap.put("money", new DecimalFormat("#.00").format((data3 / 90) * 0.01)); // 捐赠金额根据用户总的平板支撑时间来计算,90秒捐赠0.01元
            }

            if (activityId == 14 || activityId == 15) {
                // 仰卧起坐 | 俯卧撑

                // 仰卧起坐和俯卧撑如果不打满4组,不算做一次打卡
                if (((BigDecimal) launchPageInfoMap.get("currData")).intValue() != 4) {
                    weekLaunchTag[(((GregorianCalendar) Calendar.getInstance()).get(Calendar.DAY_OF_WEEK) + 5) % 7] = 0;
                }


                activityPageMap.put("progress", ((BigDecimal) launchPageInfoMap.get("currData")));
                activityPageMap.put("numPerGroup", Integer.parseInt((String) launchPageInfoMap.get("data1")));

                int data3 = (int) launchPageInfoMap.get("data3");
                activityPageMap.put("todayCount", data3); // 今日累积坚持个数

                data3 = (data3 > 720) ? 720 : data3; // 每日捐献金额有限制
                activityPageMap.put("money", new DecimalFormat("#.00").format((data3 / 80) * 0.01)); // 捐赠金额根据用户总的平板支撑时间来计算,80个0.01元
            }

        } else {
            /**
             * 今天未打卡
             */
            if (activityId == 11) {
                Map gongyipaoMapFixed = activityDaoFixed.getGongyipaoLaunchCardInfoFixed(userId);
                // 公益跑
                Map<String, Object> userBodyInfoMap = userDao13.getUserBodyInfo(userId); // 获取身高体重信息,用来计算跑路里程和卡路里
                activityPageMap.put("mileCount", "0");
                activityPageMap.put("calorie", "0");
                activityPageMap.put("timeCount", "0");

                if (gongyipaoMapFixed != null) {

                    try {
                        activityPageMap.replace("mileCount", ((BigDecimal) gongyipaoMapFixed.get("mileCount")).doubleValue());
                        double calorie = ((BigDecimal) userBodyInfoMap.get("weight")).intValue() * ((BigDecimal) gongyipaoMapFixed.get("mileCount")).doubleValue();
                        activityPageMap.replace("calorie", calorie);
                    } catch (Exception exception) {

                    }
                }
            }

            if (activityId == 12) {
                // 骑行
                activityPageMap.put("currMileNumber", 0);
                activityPageMap.put("mileCount", launchPageInfoMap.get("currDataCount"));
            }

            if (activityId == 13) {
                // 平板支撑
                activityPageMap.put("topRecord", launchPageInfoMap.get("maxCurrData")); // 发送时间为long类型的最高数据
            }

            if (activityId == 14 || activityId == 15) {
                // 仰卧起坐 | 俯卧撑
                activityPageMap.put("numPerGroup", 20); // 默认20组
                activityPageMap.put("progress", 0); // 默认进度为0
            }
        }

        // 一周打卡情况
        activityPageMap.put("today", ((GregorianCalendar) Calendar.getInstance()).get(Calendar.DAY_OF_WEEK));
        activityPageMap.put("MON", weekLaunchTag[0]);
        activityPageMap.put("TUE", weekLaunchTag[1]);
        activityPageMap.put("WED", weekLaunchTag[2]);
        activityPageMap.put("THU", weekLaunchTag[3]);
        activityPageMap.put("FRI", weekLaunchTag[4]);
        activityPageMap.put("SAT", weekLaunchTag[5]);
        activityPageMap.put("SUN", weekLaunchTag[6]);

        return JSONObject.fromObject(activityPageMap).toString();
    }


    /**
     * 打卡
     */
    @Override
    public String launchActivity(int activityId, int userId, Object data) {

        Map launchPageInfoMap = activityDao.getUserLaunchPageInfo(userId, activityId);

        java.util.Date date = (java.util.Date) launchPageInfoMap.get("date");
        long time = Calendar.getInstance().getTime().getTime() - date.getTime();
        boolean hasLaunched = false;
        boolean launchResult = true;

        if (time >= 0 && time <= 86400000) {
            hasLaunched = true;
        }


        if (activityId == 11) {
            // 公益跑

            int currData = (int) ((double) data);
            if (!hasLaunched) {
                // 今天未打卡

                // 获取身高体重信息,用来计算跑路里程和卡路里
                Map<String, Object> userBodyInfoMap = userDao13.getUserBodyInfo(userId);
                activityDao.addNewLaunchRecord(userId, activityId, String.valueOf(currData), "", 0, 20, 0.05);
                activityDao.addUserActivityCoin(userId, activityId, 10); // 用户当日首次打卡增加10积分
            } else {
                // 今天已打卡
                int currDataNew = currData + ((BigDecimal) launchPageInfoMap.get("currData")).intValue();
                Map<String, Object> userBodyInfoMap = userDao13.getUserBodyInfo(userId);
                String mileCount = ((BigDecimal) activityDaoFixed.getGongyipaoTodayMile(userId)).toString();

                if (Double.parseDouble(mileCount) > 30) {
                    mileCount = "30";
                }
                activityDao.addLaunchRecord(userId, activityId, String.valueOf(currDataNew), mileCount, 30, 0.05);
            }

        }

        if (activityId == 12) {
            // 骑行
            double currData = (double) data;
            if (!hasLaunched) {
                // 今天未打卡
                activityDao.addNewLaunchRecord(userId, activityId, String.valueOf(currData), "", 0, 0, 0);
                activityDao.addUserActivityCoin(userId, activityId, 10); // 用户当日首次打卡增加10积分
            } else {
                // 今天已打卡
                double currDataNew = currData + ((BigDecimal) launchPageInfoMap.get("currData")).doubleValue();
                activityDao.addLaunchRecord(userId, activityId, String.valueOf(currDataNew), "", 10, 0);
            }
        }

        if (activityId == 13) {
            // 平板支撑
            long currData = (long) ((double) data);

            if (!hasLaunched) {
                // 今天未打卡
                double money = 0.01; // 当日首次打卡赠送0.01元

                activityDao.addNewLaunchRecord(userId, activityId, String.valueOf(currData), "", (int) currData / 100, 0, money);
                activityDao.addUserActivityCoin(userId, activityId, 10); // 用户当日首次打卡增加10积分
            } else {
                // 今天已打卡
                long currDataNew = currData;
                // int data3 = (int) launchPageInfoMap.get("data3");

                /*// 平板支撑每天最多捐献0.1元,每90秒0.01元,初始打卡0.01元,至多有效个数是810个
                if ((data3 + currDataNew / 100) > 810) {
                    currData = 81000 - data3 * 100;
                }*/

                activityDao.freshLaunchRecord(userId, activityId, String.valueOf(currDataNew), (int) currData / 100, 10, 0.01);
            }
        }

        if (activityId == 14 || activityId == 15) {
            // 仰卧起坐 | 俯卧撑
            try {
                // 安卓端使用的是组数数据,progress服务器来管理
                int currData = (int) ((double) data);
                if (!hasLaunched) {
                    // 今天未打卡
                    double money = 0.01;
                    activityDao.addNewLaunchRecord(userId, activityId, String.valueOf(1), String.valueOf(currData), currData, 0, money);
                    activityDao.addUserActivityCoin(userId, activityId, 10); // 用户当日首次打卡增加10积分
                } else {
                    // 今天已打卡
                    Map<String, Object> userTodayActivityInfo = activityDao.getUserTodayActivityInfo(userId, activityId);

                    if (userTodayActivityInfo != null) {
                        int progress = ((BigDecimal) userTodayActivityInfo.get("currData")).intValue();

                        // 一天打卡多次时初始化进度
                        if (progress + 1 > 4) {
                            progress = 0;
                        }

                        // int data3 = (int) launchPageInfoMap.get("data3");

                        // 仰卧起坐和俯卧撑每天最多捐献0.1元,初始打卡0.01元,80个0.01元,最多有效个数是720个
                        /*if ((data3 + currData) > 720) {
                            currData = 720 - data3;
                        }*/

                        activityDao.freshLaunchRecord(userId, activityId, String.valueOf(progress + 1), currData, 10, 0.01);
                    }

                }
            } catch (Exception exception) {
                // iOS端使用的是每组个数和进度作为data
                JSONObject jsonObject = JSONObject.fromObject((LinkedTreeMap) data);
                int numPerGroup = jsonObject.getInt("numPerGroup");
                int progress = jsonObject.getInt("progress");

                // 每天重复打卡时,初始化进度
                if (progress > 4) {
                    progress = 0;
                }

                if (!hasLaunched) {
                    // 今天未打卡
                    double money = numPerGroup / 80 * 0.01;
                    activityDao.addNewLaunchRecord(userId, activityId, String.valueOf(progress), String.valueOf(numPerGroup), numPerGroup, 0, money);
                    activityDao.addUserActivityCoin(userId, activityId, 10); // 用户当日首次打卡增加10积分
                } else {
                    // 今天已打卡
                    /*int data3 = (int) launchPageInfoMap.get("data3");
                    if ((data3 + numPerGroup) > 720) {
                        numPerGroup = 720 - data3;
                    }*/

                    activityDao.freshLaunchRecord(userId, activityId, String.valueOf(progress), numPerGroup, 10, 0.01);
                }
            }


        }


        String activityPageInfo = activityPage(activityId, userId);
        JSONObject activityNewPageInfo = JSONObject.fromObject(activityPageInfo);
        activityNewPageInfo.put("launchResult", launchResult);

        return activityNewPageInfo.toString();
    }


    /**
     * 用户自己输入里程数
     *
     * @param mile
     * @param userId
     * @return
     */
    @Override
    public String inputMile(double mile, int userId) {
        return new MapToJson("result", activityDaoFixed.inputMile(mile, userId)).toJsonString();
    }
}
